import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  HostBinding,
  OnInit,
} from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { combineLatest, concat, from, merge, Observable } from 'rxjs';
import { filter, map, switchMap, take, toArray } from 'rxjs/operators';
import { listAnimation, slideToRight } from 'src/app/anims';
import { Project } from 'src/app/domain';
import { ProjectService } from 'src/app/services/project.service';
import { ConfirmDialogComponent } from 'src/app/shared';
import { InviteComponent } from '../invite';
import { NewProjectComponent } from '../new-project';
import * as _ from 'lodash';

@Component({
  selector: 'app-project-list',
  templateUrl: './project-list.component.html',
  styleUrls: ['./project-list.component.scss'],
  animations: [slideToRight, listAnimation],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ProjectListComponent implements OnInit {
  @HostBinding('@routeAnim') state;

  projects$: Observable<Project[]>;
  projects;

  constructor(
    private dialog: MatDialog,
    private cd: ChangeDetectorRef,
    private projectService: ProjectService
  ) { }

  ngOnInit(): void {
    this.projects$ = this.projectService.get(
      '37489e0c-df34-c261-71c4-ce75357e3035'
    );
    this.cd.markForCheck();
  }

  openNewProjectDialog(): void {
    const selectedImg = `/assets/img/covers/${Math.floor(
      Math.random() * 40
    )}_tn.jpg`;
    const dialogRef = this.dialog.open(NewProjectComponent, {
      data: {
        thumbnails: this.getThumbnails(),
        img: selectedImg,
      },
    });

    dialogRef
      .afterClosed()
      .pipe(
        take(1),
        filter((n) => n),
        map((val) => ({ ...val, coverImg: this.buildImgSrc(val.coverImg) })),
        switchMap((v) => this.projectService.add(v))
      )
      .subscribe((project) => {
        this.projects$ = this.projects$.pipe(map((item) => item));
        this.cd.markForCheck();
      });
  }

  launchInviteDialog(): void {
    const dialogRef = this.dialog.open(InviteComponent, {
      data: {
        members: []
      }
    });
  }

  launchUpdateDialog(project: Project): void {
    const dialogRef = this.dialog.open(NewProjectComponent, {
      data: {
        thumbnails: this.getThumbnails(),
        project,
      },
    });

    dialogRef
      .afterClosed()
      .pipe(
        take(1),
        filter((n) => n),
        map((val) => ({ ...val, coverImg: this.buildImgSrc(val.coverImg) })),
        switchMap((v) => this.projectService.update(v))
      )
  }

  launchDeleteDailog(project): void {
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      data: {
        title: '删除项目：',
        content: '确认要删除该项目？',
      },
    });

    dialogRef.afterClosed().subscribe((result) => {
      console.log(result, '....');
      this.projects$ = this.projects$.pipe(
        map((item) => item.filter((p) => p.id !== project.id))
      );
      this.cd.markForCheck();
      // dialogRef
      // .afterClosed()
      // .pipe(
      //   take(1),
      //   filter((n) => n),
      //   map((val) => ({ ...val, coverImg: this.buildImgSrc(val.coverImg) })),
      //   switchMap((v) => this.projectService.del(project))
      // ).subscribe(prj => {
      //     this.projects$ = this.projects$.pipe(
      //     map((item) => item.filter((p) => p.id !== project.id))
      //   );
      // })
    });
  }

  private getThumbnails(): string[] {
    return _.range(0, 40).map((i) => `/assets/img/covers/${i}_tn.jpg`);
  }

  private buildImgSrc(img: string): string {
    return img.indexOf('_') > -1 ? img.split('_')[0] + '.jpg' : img;
  }
}
